package com.example.administrator.myview;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.example.administrator.myview.mvvm.dataBinding.DataBindActivity;
import com.example.administrator.myview.recycleView.RecycleSearchActivity;
import com.example.administrator.myview.sql.SqLiteActivity;
import com.example.administrator.myview.util.DownLoadFile;
import com.example.administrator.myview.util.HandlerThread;
import com.example.administrator.myview.util.MyUtils;
import com.example.administrator.myview.voice.RecorderActivity;
import com.example.administrator.myview.webview.WebViewActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLDecoder;
import java.util.Map;

import sjj.permission.PermissionCallback;
import sjj.permission.model.Permission;
import sjj.permission.util.PermissionUtil;

public class MainActivity extends AppCompatActivity  {

    //支付宝订单测试
    private static final int SDK_PAY_FLAG = 102;					//支付宝支付
    String orderInfo="app_id=2016101802225149&biz_content=%7b%22body%22%3a%22%22%2c%22subject%22%3a%22%5cu8FDE%5cu8863%5cu88D9%5cu751C%5cu7F8Errrff%5cu4EBA%5cu4EBA%5cu5E7F%5cu544A%5cu54C8%5cu54C8%5cu54C8%5cu54C8%5cu54C8%5cu54C8%22%2c%22out_trade_no%22%3a%22201711040823556559%22%2c%22timeout_express%22%3a%2230m%22%2c%22total_amount%22%3a%220.01%22%2c%22seller_id%22%3a%22%22%2c%22product_code%22%3a%22QUICK_MSECURITY_PAY%22%7d&charset=utf-8&format=json&method=alipay.trade.app.pay&notify_url=https%3a%2f%2fapp.90hr.net%2fAPI%2falipay%2fAlipayAppNotify.aspx&sign=hsTRFy31PQkEegI4AZE75iydycbOrAURSjbDMnu71z5hc7ls0096feGZ3tOGI8x9vUTcCURIMNnw1FhjaeNGUq2ChUeegbsu0C88kQedmjlo74lhi5qvKaUMrAZkozU%2ffmIDlU9dNRiM2X8hXxL4y71t3inC%2b9pYs8busO7FQJg%3d&sign_type=RSA&timestamp=2017-11-04%2008%3a16%3a21&version=1.0";
    //富文本
    private static final String IMAGE3 ="<p><font color=\\\"#ff0000\\\">富文本 this is a test</font></p>\n"
            + "<p><img src=\"/D/1/F/1_qq_24956515.jpg\" alt=\"Image\"/></p>" ;

    IWXAPI msgApi;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //图片闪烁功能
        ImageView imageView=(ImageView)findViewById(R.id.imageView);
        setFlickerAnimation(imageView);

        //跳转webView测试页面
        final TextView test=(TextView)findViewById(R.id.web);
        test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MainActivity.this,WebViewActivity.class);
                startActivity(intent);
                //从左边向右 跳转动画 返回动画应该在第二类写
                overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
                // overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
            }
        });

        //支付宝
        findViewById(R.id.pay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                payOrderWithAliPay(orderInfo);
            }
        });

        //通过url下载app功能 下载后提醒安装
        findViewById(R.id.down).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //应该开子线程
                Toast.makeText(MainActivity.this,"下载文件",Toast.LENGTH_LONG).show();
              new DownLoadFile(MainActivity.this,"https://www.2298.com/app/download/qh2298_seller_android.apk");
            }
        });


        //webView加载富文本
        WebView webView=(WebView)findViewById(R.id.webView);
        webView.loadDataWithBaseURL("http://avatar.csdn.net",IMAGE3,"text/html", "UTF-8", null);


        //微信支付初始化  wx17e52c578aea5ff1  wxb4ba3c02aa476ea1
        msgApi = WXAPIFactory.createWXAPI(MainActivity.this, "wx17e52c578aea5ff1");
        // 将该app注册到微信 括号里是appId
        msgApi.registerApp("wx17e52c578aea5ff1");//key不对
        //初始化回调监听 把微信的回到结果类拿到 拿到回调消息进行处理
        MyAppLication mAPP = (MyAppLication) getApplication();
        mAPP.setWxPayCallbackHandler(new WxPayCallbackHandler());
        findViewById(R.id.wx_pay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                payOrderWithWeiXin();
            }
        });

        //初始化通知
        initNotify();
        findViewById(R.id.notify).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showIntentActivityNotify("测试","我的通知");
            }
        });


        //录音页面
        findViewById(R.id.go_recorder).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //权限判断
                PermissionUtil.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO},
                        new PermissionCallback() {
                            @Override
                            public void onGranted(Permission permissions) {
                                Intent intent=new Intent(MainActivity.this, RecorderActivity.class);
                                startActivity(intent);
                            }

                            @Override
                            public void onDenied(Permission permissions) {

                            }
                        });

            }
        });

        //网络请求示例
        doInternet();


        findViewById(R.id.recycleView).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MainActivity.this, RecycleSearchActivity.class);
                startActivity(intent);
            }
        });


        //MVVM dataBinding
        findViewById(R.id.dataBind).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyUtils.start_activity(MainActivity.this, DataBindActivity.class);
            }
        });


        //sql数据库操作类
        findViewById(R.id.sql).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyUtils.start_activity(MainActivity.this, SqLiteActivity.class);
            }
        });



    }

    private void doInternet() {
        //其中一种网络加载数据请求实例（不带布局）
        HandlerThread handlerThread=new HandlerThread(this,true);//自己处理
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("","");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        handlerThread.doThreadStart(false,"",jsonObject.toString());
        //这一种是本地布局显示成网络加载 加载成功后再显示 第四个参数是是否显示旋转等待进度条
        //xm布局要用一个FrameLayout和LinearLayout包裹
        //handlerThread.initNetLayout((FrameLayout)findViewById(R.id.layAll), (LinearLayout)findViewById(R.id.layDispAll));	//初始化等待面板和等待动画
      //  handlerThread.doThreadStartWithNet(false,"",jsonObject.toString());
        //返回结果
        handlerThread.setHandlerThread(new HandlerThread.ThreadCallBack() {
            @Override
            public void ProcessStatusSuccess(JSONObject obj) throws Exception {
                  //成功
            }

            @Override
            public void ProcessStatusError(int errType, int errCode, String errMsg) {
                  //失败
            }
        });
    }

    NotificationCompat.Builder mBuilder;
    NotificationManager mNotificationManager;
    private void initNotify(){
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(getApplicationContext());
        mBuilder.setContentTitle("测试标题")
                .setContentText("测试内容")
                // .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL))
//              .setNumber(number)//显示数量
                .setTicker("测试通知来啦")//通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示
                .setPriority(Notification.PRIORITY_DEFAULT)//设置该通知优先级
//              .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                .setOngoing(false)//ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
//              .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合：
                //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission
                .setSmallIcon(R.drawable.ic_launcher);
    }

    public void showIntentActivityNotify(String who,String what){
        // Notification.FLAG_ONGOING_EVENT --设置常驻
        // Flag;Notification.FLAG_AUTO_CANCEL 通知栏上点击此通知后自动清除此通知
        //  notification.flags = Notification.FLAG_AUTO_CANCEL;//在通知栏上点击此通知后自动清除此通知
        mBuilder.setAutoCancel(true)//点击后让通知将消失
                .setContentTitle(who)
                .setContentText(what)
                .setWhen(System.currentTimeMillis())
                .setTicker("您有未读消息");
        //点击的意图ACTION是跳转到Intent
        Intent resultIntent = new Intent(this, MainActivity.class);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);
        mNotificationManager.notify(0, mBuilder.build());
    }



    private void setFlickerAnimation(ImageView iv_chat_head) {
        final Animation animation = new AlphaAnimation(1, 0); // Change alpha from fully visible to invisible
        animation.setDuration(500); // duration - half a second
        animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
        animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely
        animation.setRepeatMode(Animation.REVERSE); //
        iv_chat_head.setAnimation(animation);
    }

    //支付宝
    private void payOrderWithAliPay(String info) {
        final String orderInfo = info;   // 这个值从后台获取 订单信息
        // 必须异步调用
        new Thread(new Runnable() {

            @Override
            public void run() {
                //调用支付宝插件支持
                PayTask aliPay = new PayTask(MainActivity.this);
                Map<String, String> result = aliPay.payV2(orderInfo,true);//第二个参数是是否显示进度
                //返回结果
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandlerAliPay.sendMessage(msg);
            }
        }).start();
    }

    //返回支付结果
    @SuppressLint("HandlerLeak")
    private Handler mHandlerAliPay = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    //支付宝返回的关键字
                    String resultStatus = "";//支付返回状态码
                    String memo = "";
                    @SuppressWarnings("unchecked")//防止警告
                            Map<String, String> rawResult = (Map<String, String>) msg.obj;
                    for (String key : rawResult.keySet()) {
                        if (TextUtils.equals(key, "resultStatus")) {
                            resultStatus = rawResult.get(key);
                        } else if (TextUtils.equals(key, "memo")) {
                            memo = rawResult.get(key);
                        }
                    }

                    //对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(MainActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        if (memo.length() <= 0) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setTitle("错误信息");
                            builder.setCancelable(false);
                            builder.setMessage("支付宝支付失败");
                            builder.setPositiveButton("确定", null);
                            if (!isFinishing()) builder.show();
                        } else {
                            Toast.makeText(MainActivity.this, "支付失败"+memo+"("+resultStatus+")", Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    //支付订单调用接口 - 微信支付 没打包应该无法支付成功
  String  payData="%7b%22appid%22%3a%22wx17e52c578aea5ff1%22%2c%22noncestr%22%3a%2251074404ef83445c9fb0f69ba2fe2bd2%22%2c%22package%22%3a%22Sign%3dWXPay%22%2c%22partnerid%22%3a%221219982701%22%2c%22prepayid%22%3a%22wx2017111515063926fc5c6f720771607009%22%2c%22sign%22%3a%22DF2951E9B0B50F4EEDBC309DF45CCFDD%22%2c%22timestamp%22%3a%221510729602%22%7d";
    //PayId：订单支付ID；PayTitle：订单名称；PayOffline：订单金额
    void payOrderWithWeiXin() {
        JSONObject obj;
        try {
            obj = new JSONObject(URLDecoder.decode(payData,"UTF-8"));
            PayReq req = new PayReq();
            req.appId			= obj.getString("appid");
            req.partnerId		= obj.getString("partnerid");
            req.prepayId		= obj.getString("prepayid");
            req.nonceStr		= obj.getString("noncestr");
            req.timeStamp		= obj.getString("timestamp");
            req.packageValue	= obj.getString("package");
            req.sign			= obj.getString("sign");
            req.extData			= "app data"; // optional
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            msgApi.sendReq(req);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //支付订单调用接口 - 微信支付 先导入jar 这是官方demo里的
    //PayId：订单支付ID；PayTitle：订单名称；PayOffline：订单金额
//    void payOrderWithWeiXin() {
//        String url = "http://wxpay.wxutil.com/pub_v2/app/app_pay.php";
//        byte[] buf = Util.httpGet(url);//请求后台服务返回json串 订单信息串
//        if (buf != null && buf.length > 0) {
//            String content = new String(buf);
//            Log.e("get server pay params:",content);
//            JSONObject json =null;
//            if(null != json && !json.has("retcode")){
//                PayReq req = new PayReq();
//                try {
//                    json = new JSONObject(content);//json此处就是解析后的json
//                    req.appId			= json.getString("appid");
//                    req.partnerId		= json.getString("partnerid");
//                    req.prepayId		= json.getString("prepayid");
//                    req.nonceStr		= json.getString("noncestr");
//                    req.timeStamp		= json.getString("timestamp");
//                    req.packageValue	= json.getString("package");
//                    req.sign			= json.getString("sign");
//                    req.extData			= "app data"; // optional
//                    Toast.makeText(MainActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show();
//                    // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
//                    msgApi.sendReq(req);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }

    //支付回调 - 微信支付
    @SuppressLint("HandlerLeak")
    public final class WxPayCallbackHandler extends Handler {
        @Override
        public void handleMessage(Message m) {
            super.handleMessage(m);
            if(m.what == 1) { // 更新UI
                int iRet = m.getData().getInt("retCode");
                String sMsg = m.getData().getString("retMsg");
                if (iRet==0) {	//支付成功
                    Toast.makeText(MainActivity.this,"支付成功"+sMsg, Toast.LENGTH_LONG).show();	//支付失败，错误代码：
                    //doGetOrderStatus();	//获取订单支付状态（共用）
                }
                if (iRet==-1) {	//支付错误
                    if (sMsg == null) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle("错误提示");
                        builder.setCancelable(false);
                        builder.setMessage("微信支付失败");	//微信支付失败，请手动启动你的微信检查账户是否正常！
                        builder.setPositiveButton("确定", null);
                        if (!isFinishing()) builder.show();
                    } else {
                        Toast.makeText(MainActivity.this,"支付失败"+sMsg, Toast.LENGTH_LONG).show();	//支付失败，错误代码：
                    }
                }
                if (iRet==-2) {	//支付取消
                    Toast.makeText(MainActivity.this, "支付取消", Toast.LENGTH_SHORT).show();	//支付取消
                }
            }
        }
    }


}
